package com.elf.bluetoothtest.activity;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.elf.bluetoothtest.bluetooth.BleBluetoothConnection;
import com.elf.bluetoothtest.bluetooth.IBlueToothConnection;
import com.elf.bluetoothtest.databinding.ActivityBluetoothServiceBinding;
import com.elf.bluetoothtest.utils.ByteUtil;
import com.elf.bluetoothtest.widget.CharacteristicWidget;
import com.elf.bluetoothtest.widget.ServiceWidget;

import java.util.List;

import static android.view.View.FOCUS_DOWN;

public class BluetoothServiceActivity extends BaseActivity {

    private ActivityBluetoothServiceBinding binding;

    private BluetoothDevice bluetoothDevice;
    private BleBluetoothConnection blueToothConnection;

    private BluetoothGattCharacteristic notifyCharacteristic, writeCharacteristic;
    private Handler handler=new Handler(Looper.getMainLooper());
    private int selectType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_bluetooth_operate);
        binding = ActivityBluetoothServiceBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        bluetoothDevice = (BluetoothDevice) getIntent().getParcelableExtra("device");
        binding.tvMac.setText(bluetoothDevice.getAddress());

        showStatus(false);

        blueToothConnection = new BleBluetoothConnection(this, bluetoothDevice);
        blueToothConnection.setBluetoothConnectionListener(new IBlueToothConnection.BluetoothConnectionListener() {
            @Override
            public void onConnected(BluetoothDevice device) {
                runOnUiThread(() -> {
                    showStatus(true);
                    showUUID();
                });

            }

            @Override
            public void onDisconnected(BluetoothDevice device) {
                runOnUiThread(() -> {
                    showStatus(false);
                });
            }
        });
        blueToothConnection.setBLEOperationListener(new BleBluetoothConnection.BLEOperationListener() {
            @Override
            public void onCharacteristicRead(BluetoothGattCharacteristic characteristic, int status) {

            }

            @Override
            public void onCharacteristicChanged(BluetoothGattCharacteristic characteristic) {
                showSendMessage("收", ByteUtil.bytesToHexString(characteristic.getValue()));
            }

            @Override
            public void onCharacteristicWrite(BluetoothGattCharacteristic characteristic, int status) {
                runOnUiThread(() -> {
                    if (status == BluetoothGatt.GATT_SUCCESS) {
                        showSendMessage("发", ByteUtil.bytesToHexString(characteristic.getValue()));
                        showToast("发送成功");
                    } else {
                        showToast("发送失败");
                    }
                });
            }
        });
        blueToothConnection.connect();

        binding.layoutService.setVisibility(View.GONE);
        binding.layoutOp.setVisibility(View.VISIBLE);

        binding.btnNotify.setOnClickListener(v -> {
            selectType = 1;
            selectCh();
        });
        binding.btnWrite.setOnClickListener(v -> {
            selectType = 2;
            selectCh();
        });
        binding.btnSend.setOnClickListener(v -> {
            String text = binding.txtSendMessage.getText().toString();
            if (TextUtils.isEmpty(text)) {
                return;
            }
            byte[] data = ByteUtil.hexStringToByte(text);

            String s_time = binding.txtTime.getText().toString();
            long time = Long.parseLong(s_time);


            if (writeCharacteristic != null) {
                blueToothConnection.writeCharacteristicValue(writeCharacteristic, data, time);
//                if (writeCharacteristic.setValue(ByteUtil.hexStringToByte(text))) {
////                    showToast("发送成功");
////                    showSendMessage("发",text);
//                } else {
////                    showToast("发送失败");
//                }
            }
        });
    }

    private void showStatus(boolean b) {
        if (b) {
            binding.tvStatus.setText("已连接");
            binding.tvStatus.setTextColor(Color.BLUE);
        } else {
            binding.tvStatus.setText("未连接");
            binding.tvStatus.setTextColor(Color.RED);
        }
    }

    private void showUUID() {

        binding.layoutContent.removeAllViews();

        List<BluetoothGattService> serviceList = blueToothConnection.getServices();
        for (BluetoothGattService service : serviceList) {

            ServiceWidget serviceWidget = new ServiceWidget(this);
            serviceWidget.setData(service);
            binding.layoutContent.addView(serviceWidget);

            List<BluetoothGattCharacteristic> characteristicList = service.getCharacteristics();
            for (BluetoothGattCharacteristic characteristic : characteristicList) {

                CharacteristicWidget characteristicWidget = new CharacteristicWidget(this);
                characteristicWidget.setData(characteristic);
                characteristicWidget.setOnClickListener(selectListener);
                binding.layoutContent.addView(characteristicWidget);


//                List<BluetoothGattDescriptor> descriptorList = characteristic.getDescriptors();
//                for (BluetoothGattDescriptor descriptor : descriptorList) {
//                    sb.append("        d：").append(descriptor.getUuid().toString().toUpperCase()).append("\n");
//                }
            }
        }
    }

    private View.OnClickListener selectListener = v -> {
        CharacteristicWidget widget = (CharacteristicWidget) v;
        if (selectType == 1) {
            notifyCharacteristic = widget.getCharacteristic();
            try {
                boolean result = blueToothConnection.notifyCharacteristicValueChange(notifyCharacteristic, "", true);
                if (result) {
                    showToast("监听成功");
                } else {
                    showToast("监听失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                showToast("异常：" + e.getMessage());
            }
            binding.btnNotify.setText(notifyCharacteristic.getUuid().toString());
        }
        if (selectType == 2) {
            writeCharacteristic = widget.getCharacteristic();
            binding.btnWrite.setText(writeCharacteristic.getUuid().toString());
        }
        binding.layoutService.setVisibility(View.GONE);
        binding.layoutOp.setVisibility(View.VISIBLE);
    };

    private void selectCh() {
        binding.layoutService.setVisibility(View.VISIBLE);
        binding.layoutOp.setVisibility(View.GONE);
    }

    private void showSendMessage(String type,String msg) {
        Log.i("ble", type + " - " + msg);
        runOnUiThread(() -> {
            binding.tvMessage.append(type + " -> " + msg);
            binding.tvMessage.append("\n");
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    binding.slContent.fullScroll(FOCUS_DOWN);
                }
            },100);
        });

//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                binding.slContent.scrollTo(0, Integer.MAX_VALUE);
//            }
//        }, 100);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        blueToothConnection.release();
    }

    @Override
    public void onBackPressed() {
        if (binding.layoutService.getVisibility() == View.VISIBLE) {
            binding.layoutService.setVisibility(View.GONE);
            binding.layoutOp.setVisibility(View.VISIBLE);
            return;
        }
        super.onBackPressed();
    }

    public static void open(Context context, BluetoothDevice device) {
        Intent intent = new Intent(context, BluetoothServiceActivity.class);
        intent.putExtra("device", device);
        context.startActivity(intent);
    }
}